package com.situ.mall.web.controller;

import com.category.spi.model.Category;
import com.category.spi.model.CategoryTreeDTO;
import com.mall.common.util.JsonResult;
import com.mall.model.Product;
import com.situ.mall.web.service.BrandFeignService;
import com.situ.mall.web.service.CategoryFeignService;
import com.situ.mall.web.service.ProductFeignService;
import com.situ.mall.web.service.FavoriteFeignService;
import com.mall.user.model.dto.favorite.UserFavoriteAddRequest;
import com.mall.user.model.vo.LoginUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 商品控制器
 */
@Slf4j
@Controller
public class GoodsController {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private CategoryFeignService categoryFeignService;

    @Autowired
    private BrandFeignService brandFeignService;

    @Autowired
    private FavoriteFeignService favoriteFeignService;

    /**
     * 商品列表页面
     */
    @GetMapping("/goods")
    public String goods(Model model,
                       @RequestParam(value = "keyword", required = false) String keyword,
                       @RequestParam(value = "categoryId", required = false) Long categoryId,
                       @RequestParam(value = "brandId", required = false) Long brandId,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "12") Integer size,
                       @RequestParam(value = "minPrice", required = false) Double minPrice,
                       @RequestParam(value = "maxPrice", required = false) Double maxPrice) {
        
        try {
            // 1. 获取分类树数据（用于侧边栏分类导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 2. 获取商品列表数据
            JsonResult<Map<String, Object>> goodsResult = productFeignService.getProducts(
                    keyword,
                    brandId, 
                    categoryId,
                    1,    // 只获取上架商品
                    null, // 不限制是否热销
                    page,
                    size
            );

            if (goodsResult != null && goodsResult.getData() != null) {
                Map<String, Object> data = goodsResult.getData();
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) data.get("list");
                Long total = (Long) data.get("total");
                
                model.addAttribute("products", products);
                model.addAttribute("total", total);
                
                // 分页信息
                model.addAttribute("currentPage", page);
                model.addAttribute("pageSize", size);
                model.addAttribute("totalPages", (int) Math.ceil((double) total / size));
                
                log.info("获取商品列表: 总数={}, 当前页={}, 页大小={}", total, page, size);
            }

            // 3. 如果指定了分类ID，获取当前分类信息
            if (categoryId != null) {
                JsonResult<Category> categoryInfoResult = categoryFeignService.getCategoryById(categoryId);
                if (categoryInfoResult != null && categoryInfoResult.getData() != null) {
                    model.addAttribute("currentCategory", categoryInfoResult.getData());
                }
            }

            // 4. 保存搜索条件到模型（用于页面回显和分页链接）
            model.addAttribute("keyword", keyword);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("brandId", brandId);
            model.addAttribute("minPrice", minPrice);
            model.addAttribute("maxPrice", maxPrice);

            // 5. 创建Page对象（模拟分页对象，供模板使用）
            PageInfo pageInfo = new PageInfo();
            if (goodsResult != null && goodsResult.getData() != null) {
                Map<String, Object> data = goodsResult.getData();
                @SuppressWarnings("unchecked")
                List<Product> products = (List<Product>) data.get("list");
                pageInfo.setRecords(products);
            }
            model.addAttribute("page", pageInfo);

        } catch (Exception e) {
            log.error("商品列表页面数据加载失败", e);
        }

        return "goods";
    }

    /**
     * 商品详情页面
     */
    @GetMapping("/detail")
    public String detail(Model model, @RequestParam("id") Long id, HttpServletRequest request) {
        try {
            // 1. 获取商品详情
            JsonResult<Product> productResult = productFeignService.getProductById(id);
            if (productResult != null && productResult.getData() != null) {
                Product product = productResult.getData();
                model.addAttribute("good", product);
                log.info("获取商品详情: ID={}, Name={}", id, product.getName());
            } else {
                log.warn("商品不存在: ID={}", id);
                return "redirect:/goods";
            }

            // 2. 获取分类树数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 3. 检查用户是否已收藏该商品（需要登录状态）
            try {
                LoginUserVO currentUser = getCurrentUser(request);
                if (currentUser != null) {
                    JsonResult<Boolean> favoriteResult = favoriteFeignService.checkFavoriteStatus(id);
                    if (favoriteResult != null && favoriteResult.isSuccess()) {
                        model.addAttribute("isFavorite", favoriteResult.getData());
                    }
                }
                model.addAttribute("currentUser", currentUser);
            } catch (Exception e) {
                log.warn("检查收藏状态失败: productId={}", id, e);
                model.addAttribute("isFavorite", false);
            }

            // 4. 暂时设置评价相关的默认值（等待后端评价API实现）
            model.addAttribute("reviews", java.util.Collections.emptyList());
            model.addAttribute("totalReviews", 0);
            model.addAttribute("avgRating", "0.0");

        } catch (Exception e) {
            log.error("商品详情页面数据加载失败: ID={}", id, e);
            return "redirect:/goods";
        }

        return "detail";
    }

    /**
     * 添加商品到收藏
     */
    @PostMapping("/favorite/add")
    @ResponseBody
    public JsonResult<?> addToFavorite(@RequestParam("productId") Long productId,
                                       HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            UserFavoriteAddRequest favoriteRequest = new UserFavoriteAddRequest();
            favoriteRequest.setProductId(productId);

            JsonResult<Long> result = favoriteFeignService.addFavorite(favoriteRequest);
            if (result != null && result.isSuccess()) {
                return JsonResult.success("收藏成功");
            } else {
                return JsonResult.fail(result != null ? result.getMsg() : "收藏失败");
            }

        } catch (Exception e) {
            log.error("添加收藏失败: productId={}", productId, e);
            return JsonResult.fail("收藏失败: " + e.getMessage());
        }
    }

    /**
     * 取消收藏商品
     */
    @PostMapping("/favorite/remove")
    @ResponseBody
    public JsonResult<?> removeFromFavorite(@RequestParam("productId") Long productId,
                                            HttpServletRequest request) {
        try {
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            UserFavoriteAddRequest favoriteRequest = new UserFavoriteAddRequest();
            favoriteRequest.setProductId(productId);

            JsonResult<Boolean> result = favoriteFeignService.removeFavorite(favoriteRequest);
            if (result != null && result.isSuccess()) {
                return JsonResult.success("取消收藏成功");
            } else {
                return JsonResult.fail(result != null ? result.getMsg() : "取消收藏失败");
            }

        } catch (Exception e) {
            log.error("取消收藏失败: productId={}", productId, e);
            return JsonResult.fail("取消收藏失败: " + e.getMessage());
        }
    }

    /**
     * 从Session中获取当前用户
     */
    private LoginUserVO getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object userInfo = session.getAttribute("currentUser");
            if (userInfo instanceof LoginUserVO) {
                return (LoginUserVO) userInfo;
            }
        }
        return null;
    }

    // 简单的分页信息类（用于模板）
    public static class PageInfo {
        private List<Product> records;

        public List<Product> getRecords() {
            return records;
        }

        public void setRecords(List<Product> records) {
            this.records = records;
        }
    }
} 